package mblog.core.persist.service.impl;

import mblog.core.data.DocMenu;
import mblog.core.persist.dao.DocMenuDao;
import mblog.core.persist.entity.DocMenuPO;
import mblog.core.persist.service.DocMenuService;
import mblog.core.persist.utils.BeanMapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Yu on 2017/9/21.
 */
@Service
@Transactional
public class DocMenuServiceImpl implements DocMenuService {
    @Autowired
    private DocMenuDao docMenuDao;

    @Override
    public List<DocMenu> findByParentId(long parentId) {
        // TODO Auto-generated method stub
        List<DocMenu> authMenus = new ArrayList<DocMenu>();
        List<DocMenuPO> docMenuPOs = docMenuDao.findByParentId(parentId);
        if(docMenuPOs!=null){
            for(DocMenuPO po : docMenuPOs){
                DocMenu docMenu = BeanMapUtils.copy(po);
                authMenus.add(docMenu);
            }
        }
        return authMenus;
    }

    @Override
    public List<DocMenu> tree(Long id) {
        List<DocMenu> menus = new ArrayList<>();
        DocMenuPO authMenuPO = docMenuDao.get(id);
        DocMenu authMenu = BeanMapUtils.copy(authMenuPO);
        menus.add(authMenu);
        if(authMenu.getChildren()!=null){
//			List<AuthMenu> sortedList = sort(authMenu.getChildren());
            for (DocMenu po: authMenu.getChildren()){
                menus.addAll(tree(po.getId()));
            }
        }
        return menus;
    }

    @Override
    public DocMenu get(Long id) {
        DocMenu authMenu = BeanMapUtils.copy(docMenuDao.get(id));
        return authMenu;
    }

    @Override
    public void save(DocMenu authMenu) {
        DocMenuPO po = new DocMenuPO();
        BeanUtils.copyProperties(authMenu, po);
        if(authMenu.getParent()!=null){
            po.setParent(docMenuDao.get(authMenu.getParent().getId()));
        }
        docMenuDao.saveOrUpdate(po);
    }

    @Override
    public void delete(Long id) {
        DocMenuPO authMenuPO = docMenuDao.get(id);
        if(authMenuPO.getChildren()!=null){
            for(DocMenuPO po : authMenuPO.getChildren()){
                delete(po.getId());
            }
        }
        docMenuDao.delete(authMenuPO);
    }
}
